import { getRoleApi } from "@/api/role";
import { addUserApi, deleUserApi, getUserApi, uploadUserApi } from "@/api/user";
import { DeleteOutlined, EllipsisOutlined, FormOutlined, PlusOutlined } from "@ant-design/icons";
import { ActionType, ModalForm, ProColumns, ProFormColorPicker, ProFormSelect, ProFormText, ProTable, TableDropdown } from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { Button, Dropdown, Form, Space, Tag, message } from "antd";
import { useEffect, useRef, useState } from "react";
import dayjs from 'dayjs'

const UserList = () => {
    type GithubIssueItem = {
        username: string,
        phone: string,
        password: string,
        role: number,
        time: string,
        _id: string
    }

    const [roleList, setRoleList] = useState<roleTypes[]>([])
    const getRole = useRequest(getRoleApi, {
        onSuccess: (res) => {
            setRoleList(res.result)
        }
    })

    const [form] = Form.useForm<any>();
    const columns: ProColumns<GithubIssueItem>[] = [
        {
            dataIndex: 'index',
            valueType: 'indexBorder',
            width: 48,
            title: '序号'
            
        },
        {
            title: '用户名',
            dataIndex: 'username',
            copyable: true,
            ellipsis: true,
        },
        {
            disable: true,
            title: '手机号',
            dataIndex: 'phone',
        },
        {
            disable: true,
            title: '密码',
            dataIndex: 'password',

            //   render: (_, record) => (
            //     <Space>
            //       {record.labels.map(({ name, color }) => (
            //         <Tag color={color} key={name}>
            //           {name}
            //         </Tag>
            //       ))}
            //     </Space>
            //   ),
        },
        {
            title: '用户角色',
            dataIndex: 'role',
            valueType: 'date',
            sorter: true,
            hideInSearch: true,
            render: (_, record) => (
                <Space>
                    <Tag color={roleList.find(item => item.value == record.role)?.color}>{roleList.find(item => item.value == record.role)?.label}</Tag>
                </Space>
            ),
        },
        {
            title: '时间',
            dataIndex: "time",
            render: (_, record) => (
                <Space>
                    {dayjs(record.time).format('YYYY-MM-DD HH:mm:ss')}
                </Space>
            )
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record, _, action) => [
                <div>
                    <a
                        key="editable"
                        onClick={() => {
                            action?.startEditable?.(record._id);
                        }}
                    >
                        编辑
                    </a>
                    <ModalForm<{
                        username: string,
                        password: string,
                        role: number,
                        phone: string
                        _id: string
                    }>
                        title={'用户管理'}
                        trigger={
                            <Button type="primary" danger shape="circle" icon={<FormOutlined />} size='middle' onClick={() => form.setFieldsValue(record)} style={{ marginRight: '10px' }} />
                        }
                        width={300}
                        form={form}
                        autoFocusFirstInput
                        modalProps={{
                            destroyOnClose: true,
                            onCancel: () => console.log('run'),
                        }}
                        onFinish={async (values) => {
                            let res = await uploadUserApi(values.password, form.getFieldValue('_id'), values.username, values.role, values.phone)
                            actionRef.current?.reload()

                            message.success('提交成功');
                            return true;
                        }}
                    >
                        <ProFormText width="sm" name="username" label="用户名称" />
                        <ProFormText width="sm" name="phone" label="手机号" />
                        <ProFormText width="sm" name="password" label="密码" disabled />
                        <ProFormSelect
                            options={roleList}
                            width="xs"
                            name="role"
                            label="角色选择"
                        />

                    </ModalForm>

                    <Button type="primary" shape="circle" icon={<DeleteOutlined />} size='middle' onClick={() => { deleUserApi(record._id); actionRef.current?.reload() }} />
                </div>
            ],
        },
    ];
    const actionRef = useRef<ActionType>();
    return (
        <ProTable<GithubIssueItem>
            
            columns={columns}
            actionRef={actionRef}
            cardBordered
            request={async (params = {}, sort, filter) => {
                let res = await getUserApi(params as {
                    role?: string,
                    phone?: string,
                    time?: string,
                    username?: string
                })
                return {
                    data: res.result as any
                }
            }}
            editable={{
                type: 'multiple',
            }}
            columnsState={{
                persistenceKey: 'pro-table-singe-demos',
                persistenceType: 'localStorage',
                onChange(value) {
                    console.log('value: ', value);
                },
            }}
            rowKey="id"
            search={{
                labelWidth: 'auto',
            }}
            options={{
                setting: {
                    listsHeight: 400,
                },
            }}
            form={{
                // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
                syncToUrl: (values, type) => {
                    if (type === 'get') {
                        return {
                            ...values,
                            created_at: [values.startTime, values.endTime],
                        };
                    }
                    return values;
                },
            }}
            pagination={{
                pageSize: 5,
                onChange: (page) => console.log(page),
            }}
            dateFormatter="string"
            headerTitle="用户创建"
            toolBarRender={() => [
                <ModalForm<{
                    username: string,
                    password: string,
                    role: number,
                    phone: string
                }>
                    title={'用户创建'}
                    trigger={
                        <Button type="primary" size='middle' onClick={() => { form.setFieldsValue({ password: 'qwe123' }) }} >                        <PlusOutlined />
                            新建用户</Button>
                    }
                    width={300}
                    form={form}
                    autoFocusFirstInput
                    modalProps={{
                        destroyOnClose: true,
                        onCancel: () => console.log('run'),
                    }}
                    onFinish={async (values) => {
                        let res = await addUserApi(values.phone, values.password, values.username, values.role)
                        actionRef.current?.reload()
                        message.success('提交成功');
                        return true;
                    }}
                >
                    <ProFormText width="sm" name="username" label="用户名称" />
                    <ProFormText width="sm" name="phone" label="手机号" />
                    <ProFormText width="sm" name="password" label="密码" disabled />
                    <ProFormSelect
                        options={roleList}
                        width="xs"
                        name="role"
                        label="角色选择"
                    />

                </ModalForm>,
                <Dropdown
                    key="menu"
                    menu={{
                        items: [
                            {
                                label: '1st item',
                                key: '1',
                            },
                            {
                                label: '2nd item',
                                key: '1',
                            },
                            {
                                label: '3rd item',
                                key: '1',
                            },
                        ],
                    }}
                >
                    <Button>
                        <EllipsisOutlined />
                    </Button>
                </Dropdown>,
            ]}
        />
    );
}

export default UserList